#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/4/9  20:39
# @Author: 余浪人
# @email: yulangren520@gmail.com
import os
from flask import Flask
from flask_apscheduler import APScheduler
from werkzeug.routing import BaseConverter
from flask_cors import *


class RegexConverter(BaseConverter):
    def __init__(self, map, *args):
        self.map = map
        self.regex = args[0]


def get_sys_url():  # 获取APP路径
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))).replace('\\', '/')
    return base_dir


# 注册缓存服务
def register_cache(app: Flask):
    from apps.lib.cache_sys import cache
    cache.init_app(app)


# 注册调度器
def register_scheduler(app: Flask):
    sch = APScheduler()
    sch.init_app(app)
    sch.start()


# 注册主题
def register_themes(app: Flask):
    from flask_themes2 import Themes
    Themes(app)


#  注册前台
def register_webapp(app: Flask):
    from apps.webapp import webapp_bp
    app.register_blueprint(webapp_bp)


# 注册蓝图
def register_bp(app: Flask):
    from apps.control import sys_bp
    app.register_blueprint(sys_bp)


# 注册API
def register_api(app: Flask):
    from apps.api import api_bp
    app.register_blueprint(api_bp)


# 注册web_api
def register_web_api(app: Flask):
    from apps.webapi import webApi_bp
    app.register_blueprint(webApi_bp)


# 注册邮件服务
def register_email(app: Flask):
    from flask_mail import Mail
    mail = Mail()
    mail.init_app(app=app)


# 注册数据库
def register_db(app: Flask):
    from apps.models import db
    db.init_app(app)


# 注册login服务
def register_login(app: Flask):
    app.secret_key = 'TlCms_hello'
    from apps.lib.user_login import login_manager
    login_manager.login_view = 'sys_bp.member_login'
    login_manager.login_message = u"请先登陆!"
    login_manager.session_protection = 'strong'
    login_manager.init_app(app)


# 自定义过滤器
def register_jinja_env(app: Flask):
    from apps.jinja2 import status, is_pay, pro_column_name, property, ipAddress, static, install_status
    env = app.jinja_env
    env.filters['status'] = status
    env.filters['is_pay'] = is_pay
    env.filters['pro_column_name'] = pro_column_name
    env.filters['property'] = property
    env.filters['ipAddress'] = ipAddress
    env.filters['tl_static'] = static
    env.filters['tl_install_status'] = install_status


# 注册应用
def create_app(config: str):
    app = Flask(__name__, static_url_path='')
    app.config.from_object(config)
    app.url_map.converters['regex'] = RegexConverter
    register_bp(app=app)
    register_api(app=app)
    register_web_api(app=app)
    register_db(app=app)
    register_login(app=app)
    register_jinja_env(app=app)
    register_email(app=app)
    register_scheduler(app=app)
    register_themes(app=app)
    register_webapp(app=app)
    register_cache(app=app)
    CORS(app, supports_credentials=True)
    return app
